﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Configuration;
using CompanyBussiness;

namespace Website.admin.Control
{
    public partial class cTypeProductCreate : System.Web.UI.UserControl
    {
        LanguagesManagement languageMana = new LanguagesManagement();
        ProductManagement proMana = new ProductManagement();
        NewsManagement newsMana = new NewsManagement();
        CompanyBussiness.TypeProduct typePro;
        CompanyBussiness.Language language;
        CompanyBussiness.Product pro;
        CheckValid cv = new CheckValid();
        string strFileName = "";
        bool AddOrUp = false;
        int STRtypeProductID;
        string modulCode;
        bool ImgStatus = true;

        protected void Page_Load(object sender, EventArgs e)
        {
            modulCode = Request.QueryString["Mod"];

            trDes.Visible = false;
            trDes2.Visible = false;
            //trPic.Visible = false;
            //trPicStatus.Visible = false;


            if (Request.Cookies[CONST.COOKIES_LANGUAGE] == null)
            {
                Session[CONST.SESSION_LANGUAGE] = "";
                language = languageMana.GetLanguageByCode("vi-VN");
            }
            else
            {
                Session[CONST.SESSION_LANGUAGE] = Request.Cookies[CONST.COOKIES_LANGUAGE][CONST.COOKIES_LANGUAGE_ID];
                language = languageMana.GetLanguageByID(int.Parse(Session[CONST.COOKIES_LANGUAGE].ToString()));
            }


            this.LoadDropLanguage();
            this.LoadDropTypeProduct();

            if (Request[CONST.QUERYSTRING_TYPE_PRODUCT] == null || Request.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_TYPE] == "AddCategory")
            {
                AddOrUp = false;
               // btnDelete.Visible = false;
                lbTypeAction.Text = "Tạo mới danh mục sản phẩm";
            }
            else
            {
                AddOrUp = true;
                STRtypeProductID = int.Parse(Request[CONST.QUERYSTRING_TYPE_PRODUCT]);
                this.LoadForm();
                dropLanguage.Enabled = true;
                imgTypeProduct.Visible = true;
                lbTypeAction.Text = "Cập nhật danh mục sản phẩm";
            }

            fail.Visible = false;
            success.Visible = false;
        }

        protected void LoadDropLanguage()
        {
            try
            {
                dropLanguage.Items.Clear();

                dropLanguage.DataSource = languageMana.GetLanguageList(true);
                dropLanguage.DataBind();

                if (Request.Cookies[CONST.COOKIES_LANGUAGE] != null)
                {
                    dropLanguage.SelectedValue = Request.Cookies[CONST.COOKIES_LANGUAGE][CONST.COOKIES_LANGUAGE_ID];
                }
            }
            catch (Exception)
            {
                fail.Visible = true;
                lbError.Text = "Có lỗi trong khi sử lý dữ liệu . Bạn hãy kiểm tra lại.";
            }

        }

        protected void LoadDropTypeProduct()
        {
            try
            {
                dropTypeProduct.Items.Clear();
                //dropTypeProduct.Items.Add("");

                List<TypeProduct> listType = proMana.GetParentTypeProductAll(language.LanguagesID);
                //foreach (var li in listType)
                //{
                //    dropTypeProduct.Items.Add(li.TypeProductName);
                //}
                dropTypeProduct.DataSource = proMana.GetParentTypeProductAll(language.LanguagesID);
                dropTypeProduct.DataTextField = "TypeProductName";
                dropTypeProduct.DataValueField = "TypeProductID";
                dropTypeProduct.DataBind();
                dropTypeProduct.Items.Insert(0,new ListItem("[------]", "0"));

            }
            catch (Exception)
            {
                fail.Visible = true;
                lbError.Text = "Có lỗi trong khi load dữ liệu . Bạn hãy thử lại.";
            }
        }

        protected bool GetData()
        {
            if (txtTypeProductName.Text.Trim() != "")
            {
                typePro.TypeProductName = txtTypeProductName.Text;
            }
            else
            {
                fail.Visible = true;
                lbError.Text = "Bạn chưa nhập tên của danh mục";
                return false;
            }

            if (txtTypeProductIntro.Text.Trim() != "")
            {
                if (TextBoxCounterIntro.Characters > int.Parse(ConfigurationManager.AppSettings["MaxIntroduction"].ToString()))
                {
                    fail.Visible = true;
                    lbError.Text = "Lời giới thiệu không cho phép vượt quá "+ConfigurationManager.AppSettings["MaxIntroduction"].ToString()+" ký tự.";
                    return false;
                }
                else
                {
                    typePro.TypeProductIntro = txtTypeProductIntro.Text;
                }
            }
            else
            {
                typePro.TypeProductIntro = "";
            }

            if (txtTypeProductDes.Value.ToString() != "")
            {

                typePro.TypeProductDes = txtTypeProductDes.Value.ToString();

            }
            else
            {
                typePro.TypeProductDes = "";
            }

            if (checkStatus.Checked == true)
            {
                typePro.TypeProductStatus = true;
            }
            else
            {
                typePro.TypeProductStatus = false;
            }

            typePro.LanguagesID = language.LanguagesID;

            if (dropTypeProduct.SelectedValue == "0")
            {
                typePro.ParentTypeProductID = 0;
            }
            else
            {
               // TypeProduct typ = proMana.GetTypeProductByNameSingle(dropTypeProduct.SelectedValue.ToString());
                TypeProduct typ = proMana.GetTypeProductByID(int.Parse(dropTypeProduct.SelectedValue.ToString()));
                typePro.ParentTypeProductID = typ.TypeProductID;
            }

            if (Session[CONST.SESSION_IMG_THUMBNAIL] == null)
            {
                typePro.TypeProductImg = "";
            }
            else
            {
                typePro.TypeProductImg = ConfigurationManager.AppSettings["FolderImagesUpload"] + Session[CONST.SESSION_IMG_THUMBNAIL];
            }

            if (checkImgStatus.Checked)
            {
                ImgStatus = true;
            }
            else
            {
                ImgStatus = false;
            }

            return true;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (AddOrUp == false)
                {
                    #region Addnew

                    modulCode = Request.QueryString["Mod"];

                    typePro = new TypeProduct();

                    if (GetData() == false)
                        return;
                    //tao danh muc san pham
                    int idOut= proMana.CreateTypeProduct((int)typePro.ParentTypeProductID, typePro.TypeProductName, typePro.TypeProductIntro, typePro.TypeProductDes, typePro.TypeProductImg, (Boolean)typePro.TypeProductStatus,ImgStatus, (int)typePro.LanguagesID);

                    //Tao metadata cho danh muc
                    Metadata meta = new Metadata();
                    meta.TypeProductID = idOut;
                    newsMana.CreateMetadata(meta);

                    //Cap nhat meta cho danh muc vua tao
                    Response.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_NAME] = "CreateMetadata";
                    Response.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_TYPE] = "CreateNew";
                    Response.Redirect("Administrator.aspx?" + CONST.ACTION + "=CreateMetadata&Mod=" + modulCode + "&" + CONST.QUERYSTRING_TYPE_PRODUCT + "=" + idOut);


                    LoadDropTypeProduct();
                    success.Visible = true;
                    lbSuccess.Text = "Bạn đã thêm mới danh mục thành công !";

                    this.FormatForm();

                    #endregion
                }
                else
                {
                    #region Update

                    typePro = proMana.GetTypeProductByID(STRtypeProductID);

                    if (GetData() == false)
                        return;

                    proMana.UpdateTypeProduct(STRtypeProductID, (int)typePro.ParentTypeProductID, typePro.TypeProductName, typePro.TypeProductIntro, typePro.TypeProductDes, typePro.TypeProductImg, (Boolean)typePro.TypeProductStatus,ImgStatus, (int)typePro.LanguagesID);

                    success.Visible = true;
                    lbSuccess.Text = "Bạn đã cập nhật danh mục thành công !";

                    this.FormatForm();

                    #endregion
                }
            }
            catch (Exception)
            {
                fail.Visible = true;
                lbError.Text = "Có lỗi trong khi sử lý dữ liệu . Bạn hãy kiểm tra lại.";
            }        
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            this.FormatForm();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                typePro = proMana.GetTypeProductByID(STRtypeProductID);
                //List<Product> listProduct = proMana.GetProductByTypeProductIDAll(typePro.TypeProductID);
                //if (listProduct.Count > 0)
                //{
                //    lbError.Text = "Danh mục này có chứa sản phẩm bạn không thể xóa!";
                //    return;
                //}
                proMana.DeleteTypeProduct(typePro.TypeProductID);

                Response.Cookies[CONST.ACTION][CONST.COOKIES_ACTION_NAME] = "TypeProduct";
                Response.Redirect("Administrator.aspx?" + CONST.ACTION + "=TypeProduct&Mod=" + "MPRODUCT");
            }
            catch (Exception)
            {
                fail.Visible = true;
                lbError.Text = "Có lỗi trong khi sử lý dữ liệu . Bạn hãy kiểm tra lại.";
            }
        }

        //protected void UpLoadFile()
        //{
        //    #region Upload file
        //    Boolean fileOK = false;
        //    String path = Server.MapPath("~/images/");

        //    string typeFile;
        //    if (imgUpload.HasFile)
        //    {
        //        String fileExtension = Path.GetExtension(imgUpload.FileName).ToLower();

        //        fileOK = true;

        //        if (fileOK)
        //        {
        //            if (fileExtension.ToString() == ".jpg" || fileExtension.ToString() == ".JPG" || fileExtension.ToString() == ".png" || fileExtension.ToString() == ".PNG" || fileExtension.ToString() == ".GIF" || fileExtension.ToString() == ".gif" || fileExtension.ToString() == ".bmp" || fileExtension.ToString() == ".BMP")
        //            {
        //                try
        //                {
        //                    Random rd = new Random(1000000);
        //                    int index = imgUpload.FileName.LastIndexOf('.');
        //                    typeFile = imgUpload.FileName.Substring(index - 1);

        //                    strFileName = "Picture_" + Convert.ToString(rd.Next(1000000, 9999999)) + typeFile;

        //                    imgUpload.PostedFile.SaveAs(path + strFileName);

        //                }
        //                catch (Exception ex)
        //                {
        //                    Console.Write(ex);
        //                }
        //            }
        //            else
        //            {
        //                fail.Visible = false;
        //                lbError.Text = "File của bạn không hợp lệ !";
        //            }

        //        }
        //    }
        //    #endregion
        //}

        protected void FormatForm()
        {
            try
            {
                if (AddOrUp == false)
                {
                    txtTypeProductName.Text = "";
                    txtTypeProductIntro.Text = "";
                    imgTypeProduct.ImageUrl = ConfigurationManager.AppSettings["NoImages"];
                    txtTypeProductDes.Value = "";
                    Session[CONST.SESSION_IMG] = null;
                    Session[CONST.SESSION_IMG_THUMBNAIL] = null;
                }
                else
                {
                    this.LoadForm();
                    Session[CONST.SESSION_IMG] = null;
                    Session[CONST.SESSION_IMG_THUMBNAIL] = null;
                }
            }
            catch (Exception)
            { }
        }

        protected void LoadForm()
        {
            try
            {
                typePro = proMana.GetTypeProductByID(STRtypeProductID);
                txtTypeProductName.Text = typePro.TypeProductName.ToString();

                if (typePro.TypeProductIntro != null)
                    txtTypeProductIntro.Text = typePro.TypeProductIntro.ToString();
                else
                    txtTypeProductIntro.Text = "";

                if (typePro.TypeProductDes != null)
                    txtTypeProductDes.Value = typePro.TypeProductDes.ToString();
                else
                    txtTypeProductDes.Value = "";

                dropLanguage.SelectedValue = languageMana.GetLanguageByID((int)typePro.LanguagesID).LanguagesID.ToString();
                if (typePro.ParentTypeProductID == null)
                {
                    dropTypeProduct.SelectedValue = "0";
                }
                else
                    dropTypeProduct.SelectedValue = proMana.GetTypeProductByID((int)typePro.ParentTypeProductID).TypeProductID.ToString();


                if (typePro.TypeProductStatus == true)
                    checkStatus.Checked = true;
                else
                    checkStatus.Checked = false;


                if (typePro.TypeProductImg != "" && typePro.TypeProductImg!=string.Empty)
                    imgTypeProduct.ImageUrl = typePro.TypeProductImg.ToString();
                else
                    imgTypeProduct.ImageUrl = ConfigurationManager.AppSettings["NoImages"];


                if (typePro.ImagesStatus == true)
                {
                    checkImgStatus.Checked = true;
                }
                else
                    checkImgStatus.Checked = false;

            }
            catch (Exception)
            {
                fail.Visible = true;
                lbError.Text = "Có lỗi trong khi Load dữ liệu . Bạn hãy kiểm tra lại.";
            }

        }

    }
}